#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <poll.h>
#include "Log.hpp"
#include "Socket.hpp"

#define MAX 4096
using namespace SocketModule;
using namespace LogModule;

const int gdefaultfd = -1;

class PollServer
{
public:
    PollServer(uint16_t port)
        : _port(port), _listen_socket(std::make_unique<TcpSocket>()), _isrunning(false)
    {
    }

    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        // 初始化结构体数组
        for (int i = 0; i < MAX; i++)
        {
            _fds[i].fd = gdefaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        // 将listensockfd添加到数组中
        _fds[0].fd = _listen_socket->Fd();
        _fds[0].events |= POLLIN;
    }

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            int timeout = -1;
            int n = poll(_fds, MAX, timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out..." << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                std::cout << "有事件就绪了..." << std::endl;
                Dispatcher(); // 把已经就绪的fd，派发给指定的模块
                break;
            }
        }
        _isrunning = false;
    }

    void Accepter()
    {
        InetAddr client;
        // 不会阻塞了，也就是不用等了，只用拷贝就行
        int newfd = _listen_socket->Accepter(&client);
        if (newfd < 0)
            return;
        else
        {
            std::cout << "获得了一个新链接: " << newfd << ", client info: " << client.Addr() << std::endl;
            // 把新的newfd添加到辅助数组中
            int pos = -1;
            for (int i = 0; i < MAX; i++)
            {
                if (_fds[i].fd == gdefaultfd)
                {
                    pos = i;
                    break;
                }
            }
            if (pos == -1)
            {
                // 可以对数组扩容
                LOG(LogLevel::ERROR) << "服务器已经满了...";
                close(newfd);
            }
            else
            {
                _fds[pos].fd = newfd;
                _fds[pos].events |= POLLIN;
            }
        }
    }

    void Recver(int who)
    {
        char buffer[1024];
        ssize_t n = recv(_fds[who].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;

            std::string message = "echo# ";
            message += buffer;
            send(_fds[who].fd, message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出..., sockfd: " << _fds[who].fd;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = _fds[who].revents = 0;
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取错误..., sockfd: " << _fds[who].fd;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = _fds[who].revents = 0;
        }
    }

    void Dispatcher()
    {
        for (int i = 0; i < MAX; i++)
        {
            if (_fds[i].fd == gdefaultfd)
                continue;
            if (_fds[i].fd == _listen_socket->Fd())
            {
                // 是listensockfd，并且已经添加的集合中了
                if (_fds[i].revents & POLLIN)
                {
                    Accepter();
                }
            }
            else
            {
                // 就绪的普通fd
                if (_fds[i].revents & POLLIN)
                {
                    Recver(i);
                }
            }
        }
    }
    ~PollServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    struct pollfd _fds[MAX];
};
